<!-- 编辑部门 -->
<template>
  <el-card style="max-width: 100%" shadow="always">
    <template #header>
      <el-page-header :icon="ArrowLeft" @back="() => $router.push('/crm/dept')">
        <template #content>
          <span class="text-large font-600 mr-3"> 编辑部门 </span>
        </template>
      </el-page-header>
    </template>
    <el-form :model="deptForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="部门名称">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <el-form-item label="部门职级" prop="level">
        <el-select v-model="deptForm.level" placeholder="请选择部门职级" @change="loadLeader">
          <el-option label="总经办" value="50" ></el-option>
          <el-option label="设计部" value="40" ></el-option>
          <el-option label="财务部" value="30" ></el-option>
          <el-option label="业务部" value="20" ></el-option>
          <el-option label="人事部" value="10" ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上级部门" prop="parentId">
        <el-select v-model="deptForm.parentId" placeholder="请选择上级部门" @change="GetUserList">
          <el-option v-for="item in parentDept"
                     :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人">
        <el-select v-model="deptForm.userId" placeholder="请选择负责人">
          <el-option v-for="item in headArr"
                     :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门人数">
        <el-input v-model="deptForm.peopleNum" placeholder="请输入部门人数" disabled/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </template>
  </el-card>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request";
import {useRoute, useRouter} from "vue-router";

const route = useRoute()
const router = useRouter()

//定义表单数据
const deptForm = ref({
  level:'',
  name: '',
  userId: '',
  peopleNum: '',
  parentId: '',
})

const headArr = ref([])
const listData = () => {

  request.get('/api/crm/personnel/staff/users/select').then(res => {
    headArr.value = res.data
  })
}
onMounted(() => {
  listData()
})

// //定义上级部门
// const userArr = ref([])
// const  GetUserList = ()=>{
//   let  deptId = deptForm.value.parentId
//   request.get('/api/crm/user/select?deptId='+deptId).then(res => {
//     userArr.value = res.data
//     console.log(userArr.value)
//   })
// }

// 修改后的获取上级部门方法
const userArr = ref([])
const GetUserList = async () => {
  try {
    // 1. 参数有效性校验
    const deptId = Number(deptForm.value.parentId)
    if (!deptId || isNaN(deptId)) {
      userArr.value = []
      return
    }

    // 2. 使用模板字符串防止null
    const { data } = await request.get(`/api/crm/user/select`, {
      params: { deptId }
    })

    // 3. 处理空数据情况
    userArr.value = data?.length ? data : []
    console.log('获取到的用户列表:', userArr.value)

    // 4. 空数据提示
    if (userArr.value.length === 0) {
      ElMessage.info('该部门下暂无可用人员')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取负责人列表失败')
    userArr.value = []
  }
}

//获取部门人数
const getDeptNum = async () => {
  try {
    const idParam = route.query.id
    const currentDeptId = Number(idParam)

    if (!idParam || isNaN(currentDeptId)) {
      throw new Error('部门ID参数缺失或无效')
    }

    const { data: count } = await request.get(
        `/api/crm/user/selectDeptCount?deptId=${currentDeptId}`
    )

    deptForm.value.peopleNum = count || 0 // 处理null情况
  } catch (error) {
    console.error('人数获取失败', error)
    ElMessage.error(error.message)
  }
}


const  parentDept =ref([]);
//定义加载可选上级部门数据的方法
const loadLeader = ()=>{
  //在每次加载上级部门数据前，都需要将之前遗留的直属上级部门id和可选上级部门数组数据清空
  //防止出现因新加载出来的上级部门数据里没有之前选择的人，而显示不出来上级部门名字的情况
  deptForm.value.parentId = '';
  parentDept.value = [];
  let level = deptForm.value.level;
  console.log(level);
  request.get(BASE_URL+'/api/crm/personnel/dept/select?level='+level).then(res=>{
      parentDept.value = res.data.list;
      console.log('上级部门数据:', parentDept.value)
  })
}

// const parentDept = ref([])
// const listParentDeptData = () => {
//   request.get('/api/crm/personnel/staff/dept/select').then(res => {
//     parentDept.value = res.data
//   })
// }
// onMounted(() => {
//   listParentDeptData()
// })






//提交表单
const onSubmit = () => {
  request.post('/api/crm/personnel/dept/add',deptForm.value).then(res=>{
    ElMessage.success('修改成功')
    console.log(deptForm.value)
    router.push('/crm/dept')
  })
}

//表单数
const loadDept = async () => {
  const id = route.query.id
  const res = await request.get(`/api/crm/personnel/dept/selectById?id=${id}`)
  // 保留已有数据，仅更新必要字段
  deptForm.value = {
    ...deptForm.value,
    ...res.data,
    peopleNum: deptForm.value.peopleNum // 保留已加载的人数
  }
}

onMounted(async () => {
  await loadDept() // 先加载基础数据
  await getDeptNum() // 再获取人数
  GetUserList() // 最后加载其他数据
})

//重置表单
const resetQuery = () => {
  deptForm.value = {
    level:'',
    name: '',
    userId: '',
    peopleNum: '',
    parentId: '',
  }
}
</script>

<style scoped>

</style>
